package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckitemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CheckitemServiceImpl implements CheckitemService {

    @Autowired
    private CheckItemMapper checkItemMapper;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        Page<CheckItem> p = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //如果没有 直接分页查询 返回结果
        LambdaQueryWrapper<CheckItem> wrapper = new LambdaQueryWrapper<>();
        //判断传入的数据中有没有查询条件
        if (queryPageBean.getQueryString() != null) {
            //如果有 调用模糊查询 匹配 code 或 name 列数据
            wrapper.eq(CheckItem::getCode, queryPageBean.getQueryString()).or()
                    .like(CheckItem::getName, queryPageBean.getQueryString());
        } else {
            wrapper = null;
        }
        Page selectPage = checkItemMapper.selectPage(p, wrapper);
        return new PageResult(selectPage.getTotal(), selectPage.getRecords());
    }

    @Override
    public Result add(CheckItem checkItem) {
        if (checkItem == null) {
            return new Result(false, MessageConstant.ADD_CHECKITEM_FAIL);
        }
        checkItemMapper.insert(checkItem);
        return new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
    }

    @Override
    public Result deleteById(Integer id) {
        checkItemMapper.deleteById(id);
        return new Result(true, MessageConstant.DELETE_CHECKITEM_SUCCESS);
    }

    @Override
    public Result findById(Integer id) {
        CheckItem checkItem = checkItemMapper.selectById(id);
        return new Result(true,MessageConstant.QUERY_CHECKITEM_SUCCESS ,checkItem );
    }

    @Override
    public Result edit(CheckItem checkItem) {
        checkItemMapper.updateById(checkItem);
        return new Result(true, MessageConstant.EDIT_CHECKITEM_SUCCESS);
    }

    @Override
    public Result findAll() {
        List<CheckItem> checkItems = checkItemMapper.selectList(null);
        return new Result(true,MessageConstant.QUERY_CHECKITEM_SUCCESS ,checkItems);
    }


}
